package com.sara.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread.UncaughtExceptionHandler;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

public class UncaughtExceptionUtil {

	private static UncaughtExceptionUtil instance;

	private Context mContext;

	private UncaughtExceptionUtil(Context context) {
		mContext = context;
	}

	public static void init(Activity activity) {
		instance = new UncaughtExceptionUtil(activity);
	}

	public static UncaughtExceptionUtil getInstance() {
		return instance;
	}

	private UncaughtExceptionHandler mDefaultHandler;

	public void installUncaughtExceptionHandler() {
		UncaughtExceptionHandler unhandler = Thread
				.getDefaultUncaughtExceptionHandler();
		if (unhandler != null
				&& unhandler instanceof MyUncaughtExceptionHandler)
			return;
		mDefaultHandler = unhandler;
		Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
	}

	public void unInstallUncaughtExceptionHandler() {
		Thread.setDefaultUncaughtExceptionHandler(mDefaultHandler);
	}

	private class MyUncaughtExceptionHandler implements
			Thread.UncaughtExceptionHandler {
		@Override
		public void uncaughtException(Thread thread, Throwable ex) {
			ex.printStackTrace();

			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			ex.printStackTrace(pw);
			pw.flush();
			final String stackTrace = sw.toString();

			StringBuffer report = new StringBuffer();
			report.append(Build.MANUFACTURER).append("_").append(Build.MODEL)
					.append("\n").append(stackTrace);

			Intent intent = new Intent(mContext, UncaughtExceptionService.class);
			intent.putExtra("stackTrace", report.toString());
			mContext.startService(intent);

			if (mDefaultHandler != null) {
				mDefaultHandler.uncaughtException(thread, ex);
			} else {
				Runtime.getRuntime().exit(-1);
			}
		}
	}
}
